import 'package:flutter/material.dart';

class MyApp4 extends StatefulWidget {
  MyApp4({super.key, required this.dogName});

  //定义数据,由父组件传递
  String dogName;

  @override
  //1.createState,创建组件时调用
  State<MyApp4> createState() {
    print('MyApp4---createState');
    return _MyApp4State();
  }
}

class _MyApp4State extends State<MyApp4> {
  String name = '小白';
  num age = 2;
  //2.initState,组件初始化的时候被调用
  //操作:对变量进行赋值,网络请求,更新状态
  @override
  void initState() {
    //在initState中给变量进行赋值
    print('MyApp4---initState');
    super.initState();
    name = widget.dogName;
  }

  //3.组件所依赖的数据发生变化时触发
  //只会执行一次
  @override
  void didChangeDependencies() {
    print('MyApp4---didChangeDependencies');
    super.didChangeDependencies();
  }

  //5.组建即将销毁的时候自动调用
  @override
  void deactivate() {
    print('MyApp4---deactivate');
    super.deactivate;
  }

  //6.组件销毁时自动调用
  @override
  void dispose() {
    print('MyApp4---dispose');
    super.dispose;
  }

  //4.build,组件状态更新的时候会自动调用
  //会执行多次
  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      //导航条
      appBar: AppBar(
        title: const Text(
          '组件的生命周期',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        backgroundColor: Colors.pink,
        centerTitle: true,
      ),
      body: Center(
        child: Text(
          '姓名:$name,年龄:$age岁',
          style: TextStyle(
            fontSize: 40,
            color: const Color.fromARGB(255, 8, 161, 204),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //setState所包裹的动态数据可以让视图同步更新
          setState(() {
            age = age + 1;
          });
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
